const { Transform } = require("stream");
const fs = require("fs");
const _ = require("lodash");
const utils = require('../../utils');

module.exports = function(file) {
  const stream = new Transform({ objectMode: true });
  const fd = fs.openSync(file, 'w');
  let hasTitle = false;

  stream._transform = function (chunk, encoding, callback) {
    utils.debug('mdWriter [chunk]:', chunk);
    stream.push(chunk);
    if (!hasTitle) {
      hasTitle = true;
      fs.writeSync(fd, `|${_.keys(chunk).join('|')}|\n`);
      fs.writeSync(fd, `|${_.keys(chunk).map(o=>':-:').join('|')}|\n`);
    }
    fs.write(fd, `|${_.values(chunk).join('|')}|\n`, callback);
  };

  stream.on('finish', function () {
    fs.close(fd);
    utils.debug('mdWriter [finish]');
  });

  return stream;
};